import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SubscriptionPlan } from './entities/subscription-plan.entity';

/**
 * 订阅服务
 */
@Injectable()
export class SubscriptionsService {
  constructor(
    @InjectRepository(SubscriptionPlan)
    private subscriptionPlansRepository: Repository<SubscriptionPlan>,
  ) {}
  /**
   * 获取所有订阅套餐（从数据库读取，支持后台动态配置）
   */
  async getPlans(): Promise<SubscriptionPlan[]> {
    return await this.subscriptionPlansRepository.find({
      where: { isActive: true },
      order: { sort: 'ASC', duration: 'ASC' },
    });
  }

  /**
   * 获取单个套餐信息
   */
  async getPlan(type: string, duration: number): Promise<SubscriptionPlan | null> {
    return await this.subscriptionPlansRepository.findOne({
      where: { type: type as any, duration, isActive: true },
    });
  }

  /**
   * 创建套餐（管理员）
   */
  async createPlan(data: Partial<SubscriptionPlan>): Promise<SubscriptionPlan> {
    const plan = this.subscriptionPlansRepository.create(data);
    return await this.subscriptionPlansRepository.save(plan);
  }

  /**
   * 更新套餐（管理员）
   */
  async updatePlan(id: number, data: Partial<SubscriptionPlan>): Promise<SubscriptionPlan> {
    await this.subscriptionPlansRepository.update(id, data);
    return await this.subscriptionPlansRepository.findOne({ where: { id } });
  }

  /**
   * 删除套餐（管理员）
   */
  async deletePlan(id: number): Promise<void> {
    await this.subscriptionPlansRepository.delete(id);
  }

  /**
   * 获取所有套餐（包括未启用，管理员用）
   */
  async getAllPlans(): Promise<SubscriptionPlan[]> {
    return await this.subscriptionPlansRepository.find({
      order: { sort: 'ASC', duration: 'ASC' },
    });
  }
}





